package com.cizzy.user;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.util.ArrayList;
import java.util.List;

import static com.cizzy.user.config.CizzyFinal.*;

@MapperScan("com.cizzy.user.mapper")
@SpringBootApplication
@EnableFeignClients("com.cizzy.user.feign")
@EnableAspectJAutoProxy
public class UserServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServerApplication.class, args);
        initFlowQpsRule();
        initCircuitBreakerRule();
    }

    private static void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule("user");
        // set limit qps to 2
        rule.setCount(QPS_LIMIT);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setLimitApp("default");
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    public static void initCircuitBreakerRule() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule("user");
        // 设置熔断降级阈值为 5 秒内的平均响应时间
        rule.setCount(DEGRADE_LIMIT);
        // 设置熔断降级的策略，这里选择慢调用比例
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        rule.setTimeWindow(DEGRATE_TIME_WINDOW); // 统计时间窗口为 10 秒
        rule.setMinRequestAmount(MIN_DEGRADE_NUM); // 最小请求数
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }

}
